import 'package:flutter/material.dart';
import 'package:ad_suyi_flutter_sdk/ad_suyi_ad.dart';

import 'key.dart';

class SplashPage extends StatefulWidget {
  @override
  State<StatefulWidget> createState() => _SplashState();
}

class _SplashState extends State<SplashPage> {
  ADSuyiSplashAd? _splashAd;

  @override
  Widget build(BuildContext context) {
    showSplashAd();
    return Scaffold(
      appBar: AppBar(
        title: Text("Splash"),
      ),
      body: Center(),
    );
  }

  // 开屏
  // 显示开屏广告请保证当时app内没有其他地方显示开屏广告，否则会有冲突
  void showSplashAd() {
    if (_splashAd != null) {
      return;
    }
    _splashAd = ADSuyiSplashAd(
        // posId：广告位id，
        // imgName：背景名称，
        // imgLogoName：底部logo名称，
        // isRepeatApplyPermission：用户拒绝权限后是否允许重复读取：true允许，false禁止，
        // isApplyPermission：动态申请权限：true允许，false禁止，
        posId: KeyManager.splashPosid(),
        imgName: "splash_placeholder",
        imgLogoName: "splash_logo",
        isRepeatApplyPermission: false,
        isApplyPermission: false);
    // 开屏广告关闭回调
    _splashAd?.onClosed = (AdInfo adInfo) {
      print("开屏广告关闭了 platformName : " +
          adInfo.platformName +
          " ecpmPrecision : " +
          adInfo.ecpmPrecision +
          " ecpm : " +
          adInfo.ecpm.toString());
      releaseSplashAd();
    };
    // 开屏广告加载失败回调
    _splashAd?.onFailed = (AdErrorInfo adErrorInfo) {
      print("开屏广告加载失败 errorCode : " +
          adErrorInfo.errorCode.toString() +
          " errorDescription : " +
          adErrorInfo.errorDescription);
      releaseSplashAd();
    };
    // 开屏广告曝光回调
    _splashAd?.onExposed = (AdInfo adInfo) {
      print("开屏广告曝光了 platformName : " +
          adInfo.platformName +
          " ecpmPrecision : " +
          adInfo.ecpmPrecision +
          " ecpm : " +
          adInfo.ecpm.toString());
    };
    // 开屏广告加载成功回调
    _splashAd?.onSucced = (AdInfo adInfo) {
      print("开屏广告成功了 platformName : " +
          adInfo.platformName +
          " ecpmPrecision : " +
          adInfo.ecpmPrecision +
          " ecpm : " +
          adInfo.ecpm.toString());
    };
    // 开屏广告点击回调
    _splashAd?.onClicked = (AdInfo adInfo) {
      print("开屏广告点击了 platformName : " +
          adInfo.platformName +
          " ecpmPrecision : " +
          adInfo.ecpmPrecision +
          " ecpm : " +
          adInfo.ecpm.toString());
    };
    // 加载并展示开屏 开屏也支持加载、展示分离，如有需要请参考SplashLoadShowSeparate
    _splashAd?.loadAndShow();
  }

  // 在加载失败和关闭回调后关闭广告
  void releaseSplashAd() {
    _splashAd?.release();
    _splashAd = null;
  }

  @override
  void dispose() {
    releaseSplashAd();
    super.dispose();
  }
}
